from flask import Blueprint, render_template, request, jsonify
from app.map import initGraph
from app.alg import dijkstra

main = Blueprint('main', __name__)

# 添加图缓存
graph_cache = None

def get_graph():
    global graph_cache
    if graph_cache is None:
        graph_cache = initGraph()
    return graph_cache

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/navigate', methods=['POST'])
def navigate():
    destination = request.form.get('destination')
    starting_point = request.form.get('starting_point', 'st1')  # 默认从st1开始
    
    if not destination:
        return jsonify({'error': '请输入目的地'}), 400
    
    graph = get_graph()  # 使用缓存的图数据
    route = dijkstra(graph, starting_point, destination)
    
    if route:
        return jsonify({'route': route})
    else:
        return jsonify({'error': '找不到路径或目的地不存在'}), 404

@main.route('/get_destinations')
def get_destinations():
    graph = get_graph()  # 使用缓存的图数据
    destinations = []
    
    for node in graph.node:
        if not node.startswith('st') and not node.startswith('|') and node != '---':
            destinations.append(node)
    
    return jsonify({'destinations': destinations})

@main.route('/api/find_route', methods=['POST'])
def find_route():
    """API端点：查找两点之间的路线"""
    data = request.get_json()
    
    if not data or 'start' not in data or 'end' not in data:
        return jsonify({'error': '请提供起点和终点'})
    
    start = data['start']
    end = data['end']
    
    try:
        # 使用缓存的图数据
        graph = get_graph()
        
        # 使用Dijkstra算法找到路线
        result = dijkstra(graph, start, end)
        
        # 如果结果是字符串，说明是错误信息
        if isinstance(result, str):
            return jsonify({'error': result})
            
        # 返回导航结果（只返回导航指令）
        return jsonify({
            'instructions': result['instructions']
        })
        
    except Exception as e:
        return jsonify({'error': f'导航计算出错：{str(e)}'})